<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/6
 * Time: 16:15
 */

namespace app\api\logic;

use \think\Config;

class Gps
{
    /**
     * 获取车辆GPS轨迹
     * @param int $driver_id
     * @param int $start_time
     * @param int $end_time
     * @return array轨迹
     */
    public function getTrack($driver_id=17, $start_time='2018-02-08 12:00:00', $end_time='2018-02-08 12:00:00'){
        $stime    = strtotime($start_time);
        $etime    = strtotime($end_time);
        $data     = [];
        $len      = ceil(($etime-$stime) / 3600);
        $len      = $len ? $len : 1;
        $mile     = 0;
        $lowSpeed = Config::get('base.low_speed');
        $nightTime= Config::get('base.night_time');
        $night    = explode(',',$nightTime);
        $night    = count($night)==2 ? $night : [0,24];
        list($nightStart,$nightEnd) = $night;
        $lowTime  = 0;
        $nightKm  = 0;
        $baseTime = 0;
        $totalTime= 0;
        for ($i=0; $i<=$len; $i++){
            $fileName = Config::get('base.gps_save_dir').md5($driver_id).'/'.date('YmdH', $stime + $i*3600).'.txt';
            if(file_exists($fileName)){
                $file    = file_get_contents($fileName);
                $records = explode("\r\n", trim($file));
                foreach ($records as $record) {
                    $row = explode("|", $record);
                    if($row[4]>= $stime*1000 && $row[4] <= $etime*1000){
                        $rows['driver_id']      = $row[0];
                        $rows['longitude']      = $row[1];
                        $rows['latitude']       = $row[2];
                        $rows['speed']          = $row[3];
                        $rows['time']           = $row[4];
                        $rows['accuracy']       = $row[5];
                        $rows['altitude']       = $row[6];
                        $rows['bearing']        = $row[7];
                        $rows['city']           = $row[8];
                        $rows['provider']       = $row[9];
                        $rows['mile']           = $row[10];
                        if($baseTime==0){
                            $baseTime    = $row[4];
                        }else{
                            $totalTime   = $totalTime + ($row[4] - $baseTime);
                            if($row[3]<=$lowSpeed){
                                $lowTime = $lowTime + ($row[4] - $baseTime);
                            }
                            $baseTime    = $row[4];
                        }
                        $mile                   = $mile + $row[10];
                        $hour                   = date('H',$row[4]);
                        $nightKm                = $hour >= $nightEnd || $hour<= $nightStart ? $nightKm + $mile : $nightKm;
                        array_push($data,$rows);
                    }
                }
            }
        }
        return [$mile,$lowTime,$nightKm,$data];
    }
}